<?php
declare(strict_types=1);

namespace Sdk\Fourstar;

use GuzzleHttp\Client;

class callFourStarApiUtil extends Client
{
    private $token = 'mOPf84K4A7oIrI6i/akCNgOsz5AK5xZRXpxTgQBDknU=';
    private $url = 'http://47.57.3.175:82/WebService/PublicService.asmx?wsdl';

    public function callApi($service, $params = [])
    {
        $data = $this->buildXml($service, $params);
        $response = $this->post($this->url, [
            'headers' => [
                'Content-Type' => 'text/xml; charset=utf-8',
            ],
            'body' => $data
        ]);
        if (200 == $response->getStatusCode()) {
            $serviceResult = $service . 'Result';
            $text = $response->getBody()->getContents();
            $xml = simplexml_load_string($text, 'SimpleXMLElement', 0, 'http://www.w3.org/2003/05/soap-envelope');
            $xml->registerXPathNamespace('soap', 'http://www.w3.org/2003/05/soap-envelope');
            $xml->registerXPathNamespace('ns', 'http://tempuri.org/');
            $jsonString = (string)$xml->xpath("//ns:{$serviceResult}")[0];
            $jsonArray = json_decode($jsonString, true);
            return $jsonArray['data'];
        } else {
            throw new \Exception("请求失败");
        }
    }


    public function buildXml($service, $params)
    {
        $xml = <<<EOD
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <$service xmlns="http://tempuri.org/">
      <Token>$this->token</Token>

EOD;
        if (!empty($params)) {
            foreach ($params as $key => $val) {
                $xml .= "<{$key}>{$val}</{$key}>";
            }
        }
        $xml .= <<<EOD
    </$service>
  </soap12:Body>
</soap12:Envelope>
EOD;
        return $xml;
    }

}